"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : dolphin插件
Case Name   : 有插件时，开启具体表的DML操作（SELECT除外）审计功能，设置audit_dml_state=1
Create At   : 2023.07.25
Owner       : z@wan005
Description :
    1.设置参数audit_dml_state为1
    2.创建兼容b库
    3.连接b库查询插件是否存在
    4.切换至b库执行DML操作
    5.登录数据库，查看审计日志，时间设在最接近登录数据库的时间
    6.清理环境
Expect      :
    1.成功
    2.成功
    3.插件自动加载
    4.成功
    5.查询到DML操作的信息
    6.清理环境完成
History     :
"""

import os
import re
import time
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class Plugin025(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.constant = Constant()
        self.common = Common()
        self.sh_primy = CommonSH('PrimaryDbUser')
        self.tb_name = "u_plugin0025"
        self.db_name = "db_plugin0025"
        self.default_value = self.common.show_param('audit_dml_state')

    def test_dolphin(self):
        text = '--step1:设置参数audit_dml_state为1;expect:成功--'
        self.log.info(text)
        msg = self.sh_primy.execute_gsguc('reload',
                                          self.constant.GSGUC_SUCCESS_MSG,
                                          'audit_dml_state=1')
        self.log.info(msg)
        self.assertTrue(msg, '执行失败' + text)

        text = '--step2:创建兼容b库;expect:成功--'
        self.log.info(text)
        sql_cmd = self.sh_primy.execut_db_sql(f"drop database if exists "
                                              f"{self.db_name};"
                                              f"create database "
                                              f"{self.db_name} "
                                              f"dbcompatibility ='b';")
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, sql_cmd,
                      '执行失败' + text)

        text = '--step3:连接b库查询插件是否存在;expect:插件自动加载---'
        self.log.info(text)
        sql_cmd = "select extname from pg_extension where extname " \
                  "='dolphin';"
        self.log.info(sql_cmd)
        sql_res = self.sh_primy.execut_db_sql(sql_cmd,
                                              dbname=self.db_name)
        self.log.info(sql_res)
        self.assertEqual('dolphin', sql_res.splitlines()[-2].strip(),
                         '执行失败' + text)
        self.log.info('获取此刻系统时间')
        start_time_msg = self.sh_primy.execut_db_sql('select sysdate;')
        start_time = start_time_msg.splitlines()[2].strip()
        self.log.info(start_time)
        time.sleep(5)

        text = '--step4:切换至b库执行DML操作;expect:成功--'
        self.log.info(text)
        cmd = f'''drop table if exists {self.tb_name};
        create table {self.tb_name}(id double,name text(10));
        insert into {self.tb_name} values(15489.1111478778,'liming');
        update {self.tb_name} set id=id+3.14515926;
        delete from {self.tb_name} where name='liming';'''
        res = self.sh_primy.execut_db_sql(cmd, dbname=self.db_name)
        self.log.info(res)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, res, '执行失败' + text)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, res, '执行失败' + text)
        self.assertIn(self.constant.UPDATE_SUCCESS_MSG, res, '执行失败' + text)
        self.assertIn(self.constant.DELETE_SUCCESS_MSG, res, '执行失败' + text)
        time.sleep(5)
        end_time_msg = self.sh_primy.execut_db_sql('select sysdate;')
        end_time = end_time_msg.splitlines()[2].strip()
        self.log.info(end_time)

        text = '--step5:登录数据库，查看审计日志，时间设在最接近登录数据库' \
               '的时间;expect:查询到DML操作的信息--'
        self.log.info(text)
        cmd = f"select * from pg_query_audit('{start_time}','{end_time}');"
        res = self.sh_primy.execut_db_sql(cmd, dbname=self.db_name)
        self.log.info(res)
        assert1 = re.search(f"insert.*", res, re.S)
        assert2 = re.search(f"update.*", res, re.S)
        assert3 = re.search(f"delete.*", res, re.S)
        self.assertTrue(assert1, '执行失败:' + text)
        self.assertTrue(assert2, '执行失败:' + text)
        self.assertTrue(assert3, '执行失败:' + text)

    def tearDown(self):
        text = '---step6:清理环境;expect:清理环境完成----'
        self.log.info(text)
        msg = self.sh_primy.execute_gsguc('reload',
                                          self.constant.GSGUC_SUCCESS_MSG,
                                          f'audit_dml_state='
                                          f'{self.default_value}')
        self.log.info(msg)
        cmd = f"drop database if exists {self.db_name};"
        res = self.sh_primy.execut_db_sql(cmd)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, res,
                      '执行失败' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
